package org.swingplus.core.scanner;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.swingplus.core.annotation.Autowired;
import org.swingplus.core.annotation.bean.AutoCreate;
import org.swingplus.core.annotation.widget.Button;
import org.swingplus.core.annotation.widget.Frame;
import org.swingplus.core.annotation.widget.Panel;
import org.swingplus.core.bean.MetaData;
import org.swingplus.core.bean.MetaDataType;
import org.swingplus.core.constant.widget.WidgetConstant;
import org.swingplus.core.exception.WidgetCreateException;
import org.swingplus.core.factory.WidgetFactroy;
import org.swingplus.core.util.AnnoManageUtil;
import org.swingplus.core.widget.WidgetActvity;

public class WidgetScan extends ComponentScan{
    private static final Logger logger= LoggerFactory.getLogger(WidgetScan.class);


    public static void widgetScan(Class<?> clazz){

        String packageName=clazz.getPackage().getName();
        logger.info("packageName:{}",packageName);
        System.out.println("packageName:"+packageName);
        packageName ="";
        
        //TODO 方便排查问题先去掉for循环
//        @SuppressWarnings("rawtypes")
//		Class[] widgetcollect = WidgetConstant.widgetCollect;
//        for (int i = 0; i < widgetcollect.length; i++) {
//        	Class widget = widgetcollect[i];
//        	AnnoManageUtil.getAnnotationType(packageName, widget);
//		}
//      
        MetaData metaData=AnnoManageUtil.getAnnotationType(packageName, Frame.class);

        for (MetaDataType metaDataType: metaData.getInstanceType()){

            WidgetActvity.specifyAttribute(metaDataType.getInstance(),"setUndecorated",metaDataType.getAnnotationsType());
            Map<Field,Annotation[]> fieldAnnotations =metaDataType.getMap();
            for (Field field : fieldAnnotations.keySet()) {
                Annotation[] annotations=fieldAnnotations.get(field);
//            logger.info("field================");
                logger.info("field：{}",field.getName());
                WidgetActvity.specifyAttribute(metaDataType.getInstance(),field,annotations);
            }
            ListenerScan.listenerScan(metaDataType.getInstance());


        }


        AnnoManageUtil.autowired(metaData.getInstances());





//        autowired





//        MainFrame2 dddd=(MainFrame2)metaData.getInstance();

//        dddd.initComponents();
//        dddd.initView();
//        dddd.setListeners();
//        dddd.setVisible(true);


//        fieldAnnotations.
        
        
        
        
        
        

        
        
//        AnnoManageUtil.getAnnotationType(packageName, Button.class);
//
//        AnnoManageUtil.getAnnotationType(packageName, Panel.class);


//        Annotation[] annotations = AnnoManageUtil.getAnnotationType(packageName, Frame.class);
//        for (int i = 0; i <annotations.length ; i++) {
//            System.out.println(annotations[i].annotationType().getName());
//        }
    }
public static void widgetScan(List<Object> objs){

    for (int j = 0; j < objs.size(); j++) {
        Object obj=objs.get(j);
        //类上的部件属性设置注入
        Annotation[] annos= obj.getClass().getDeclaredAnnotations();
        if(null!= annos&&0!=annos.length){
            WidgetActvity.specifyAttribute(obj,"setUndecorated",annos);
        }
        //类中的属性部件属性设置注入
        Field[] fields =obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            Annotation[] annotations=field.getAnnotations();
            if(null==annotations||annotations.length==0){
                continue;
            }
//            Autowired autowired=field.getAnnotation(Autowired.class);
//            if(null!=autowired){
//                continue;
//            }
            //忽略 AutoCreate设置false ，即为不自动创建
            AutoCreate autoCreate=field.getAnnotation(AutoCreate.class);
            if(null!=autoCreate&&!autoCreate.value()){
                continue;
            }
            field.setAccessible(true);
            try {
                Object object = field.get(obj);
                if(null==object) {
                    String className=field.getType().getName();
                    //如果直接引用的是swing或者awt中的类 创建bean,这种创建的bean只存在当前obj中,不存入容器中
                    if(className.startsWith("javax.swing.")||className.startsWith("java.awt.")) {
                        object= WidgetFactroy.create(className);
                        if(null==object) {
                            logger.error("{}'s field:{} is null",obj.getClass(), field.getName());
                            throw new WidgetCreateException("");
                        }else{
                            field.set(obj, object);
                            field.setAccessible(false);
                        }
                    }
                }
//                if(null!=object) {
//                    field.set(obj, object);
//                    field.setAccessible(false);
//                }else {
//
//                    throw new WidgetCreateException();
//                }

            } catch (IllegalArgumentException|IllegalAccessException  e1) {
                e1.printStackTrace();
            }

            logger.info("field：{}",field.getName());
            WidgetActvity.specifyAttribute(obj,field,annotations);
        }
    }






//@SuppressWarnings("rawtypes")
//		Class[] widgetcollect = WidgetConstant.widgetCollect;
//        for (int i = 0; i < widgetcollect.length; i++) {
//        	Class widget = widgetcollect[i];
//
//            for (int j = 0; j < objs.size(); j++) {
//                Object obj=objs.get(j);
//                Annotation anno= obj.getClass().getDeclaredAnnotation(widget);
//                if(null!=anno){
//                    WidgetActvity.specifyAttribute(obj,"setUndecorated",obj.getClass().getAnnotations());
//                }
//            }
//
//            Map<Field,Annotation[]> fieldAnnotations =metaDataType.getMap();
//            for (Field field : fieldAnnotations.keySet()) {
//                Annotation[] annotations=fieldAnnotations.get(field);
//
//                logger.info("field：{}",field.getName());
//                WidgetActvity.specifyAttribute(metaDataType.getInstance(),field,annotations);
//            }
//
//
//
//		}




    }


    /**
     * 针对通讯组件初始化javax.swing
     * @param obj
     */
    public static void widgetScan(Object obj){

        //类上的部件属性设置注入
        Annotation[] annos= obj.getClass().getDeclaredAnnotations();
        if(null!= annos&&0!=annos.length){
            WidgetActvity.specifyAttribute(obj,"setUndecorated",annos);
        }

            //类中的属性部件属性设置注入
            Field[] fields =obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                Annotation[] annotations=field.getAnnotations();
                if(null==annotations||annotations.length==0){
                    continue;
                }
                //忽略 AutoCreate设置false ，即为不自动创建
                AutoCreate autoCreate=field.getAnnotation(AutoCreate.class);
                if(null!=autoCreate&&!autoCreate.value()){
                    continue;
                }
                field.setAccessible(true);
                try {
                    Object object = field.get(obj);
                    if(null==object) {
                        String className=field.getType().getName();
                        //如果直接引用的是swing或者awt中的类 创建bean,这种创建的bean只存在当前obj中,不存入容器中
                        if(className.startsWith("javax.swing.")||className.startsWith("java.awt.")) {
                            object= WidgetFactroy.create(className);
                            if(null==object) {
                                logger.error("{}'s field:{} is null",obj.getClass(), field.getName());
                                throw new WidgetCreateException("");
                            }else{
                                field.set(obj, object);
                                field.setAccessible(false);
                            }
                        }
                    }
                } catch (IllegalArgumentException|IllegalAccessException  e1) {
                    e1.printStackTrace();
                }

                logger.info("field：{}",field.getName());
                WidgetActvity.specifyAttribute(obj,field,annotations);
            }
        }

}
